package com.xmgps.bdt.interfaces.bokun;

import com.xmgps.bdt.domain.bokun.prototol.BokunCmdDecoder;
import com.xmgps.bdt.domain.bokun.prototol.CMDDecoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioChannelOption;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 *
 * @author wangzezhou
 */

@Slf4j
@Service
public class DeviceCommunicationServer {

    /** 博混协议最大长度 */
    private final static int MAX_MESSAGE_SIZE = 1036;
    private static final int BOSS_THREAD_NUM = 1;
    private static final int WORKER_THREAD_NUM = 2;
    private static final int BACKLOG_SIZE = 10;

    @Value("${bokun-terminal-server.bindPort:6677}")
    private Integer bindPort;

    @Value("${bokun-terminal-server.location.kafka-topic.name}")
    private String shipLocationTopic;

    private EventLoopGroup bossGroup = new NioEventLoopGroup(BOSS_THREAD_NUM);
    private EventLoopGroup workerGroup = new NioEventLoopGroup(WORKER_THREAD_NUM);

    public DeviceCommunicationServer(){}

    public void start() throws InterruptedException {

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup);
        bootstrap.channel(NioServerSocketChannel.class);
        bootstrap.option(NioChannelOption.SO_REUSEADDR, true);
        bootstrap.option(ChannelOption.SO_BACKLOG, BACKLOG_SIZE);
        bootstrap.childOption(ChannelOption.SO_KEEPALIVE,true);

        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) {
                ch.pipeline().addLast(new CMDDecoder())
                        .addLast(new BokunCmdDecoder());
            }
        });

        bootstrap.bind(bindPort).sync();
        log.info("博琨设备通讯服务启动成功，监听端口{}",bindPort);
    }

    public void stop(){

        if (!bossGroup.isShutdown()){
            bossGroup.shutdownGracefully();
        }

        if (!workerGroup.isShutdown()){
            workerGroup.shutdownGracefully();
        }
    }
}
